import 'package:android_intent_plus/android_intent.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:sph_driver/Order/OrderList/AllOrderList.dart';
import 'package:sph_driver/Order/OrderList/CancelList.dart';
import 'package:sph_driver/Order/OrderList/EvaluateList.dart';
import 'package:sph_driver/Order/OrderList/RuningOrderList.dart';
import 'package:sph_driver/Order/OrderList/UnconfirmedList.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/RouteAct.dart';
import '../Main/EditInformation/EditCarCard.dart';
import '../http/NoLoadingGetApi.dart';
import 'WaybillDetails/FilterResultsVIew.dart';
import 'package:platform/platform.dart';


class OrderList extends StatefulWidget {
  const OrderList({super.key});
  @override


  @override
  State<OrderList> createState() => _OrderListState();
}

class _OrderListState extends State<OrderList> with SingleTickerProviderStateMixin {
  late TabController _tabController;

late int indexPage;
bool isShow=false;
String tipStr="及时的沟通可以避免很多不必要的麻烦";
  @override
  void initState() {
    super.initState();
// 初始化TabController，并指定初始索引和长度
    _tabController = TabController(initialIndex: 0, length: 5, vsync: this);
    getOrderTip();
    requestLocationPermission();

  }
  @override
  void dispose() {
// 销毁TabController
    _tabController.dispose();
    super.dispose();

  }

  void  getOrderTip()async{

    var status = await Permission.location.status;

    if (status!=PermissionStatus.denied&&status!=PermissionStatus.permanentlyDenied) {
      NoLoadinggetApiManager.getData(
        context,
        "api/system/dev/dict/list",
        {'category':'BIZ','parentId':'1795656101116833793'},
            (responseData)  {
          setState(() {
            tipStr=responseData['data'][1]['dictLabel'];
            isShow=false;
          });

        },
      );

    } else {
      NoLoadinggetApiManager.getData(
        context,
        "api/system/dev/dict/list",
        {'category':'BIZ','parentId':'1793179307134492673'},
            (responseData)  {
          setState(() {
            tipStr=responseData['data'][0]['dictLabel'];
            isShow=true;
          });

        },
      );
    }

  }


  /// 申请定位权限
  /// 授予定位权限返回true， 否则返回false
  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.location.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.location.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }


  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return  Scaffold(
        appBar:  PreferredSize(
          preferredSize: Size.fromHeight(90.h), // 设置AppBar的高度为100
          child: AppBar(
              leading: IconButton(
                onPressed: () {
                },
                icon: Icon(Icons.arrow_back_ios,size: 0,),
              ),
            backgroundColor: Colors.white,
            title:Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                GestureDetector(
                  child:  Container(
                    height: 30.h,
                    width: 220.w,//搜索框高度
                    decoration: BoxDecoration(
                      color:MyColors.backgreyColor,
                      borderRadius: BorderRadius.circular(30),
                    ),
                    child:
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        SizedBox(width: 8.w,),
                        Icon(Icons.search,color: MyColors.authTipColor,size: 18,),
                        Text("搜索我的运单",style: TextStyle(color: MyColors.authTipColor,fontSize: 12.sp),),

                      ],
                    ),


                  ),
                  onTap: ()async{
                    final result=await Navigator.push( context, FadeRoute(page:RigthDrawer(type:1,)));

                  },
                ),
                SizedBox(width: 8.w,),
                GestureDetector(

                  child: Container(
                    width: 40.w,
                    child:  Text("筛选",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 14.sp,fontWeight: FontWeight.w600),),

                  ),
                  onTap: () async {
                    final result=await Navigator.push( context, FadeRoute(page:RigthDrawer(type:2,)));

                  },
                ),

              ],
            ),
            bottom:  PreferredSize(
              preferredSize: Size.fromHeight(48.0), // 设置TabBar的高度
              child: Container(
                alignment: Alignment.centerLeft,
                child:Column(
                  children: [
                    TabBar(
                      padding: EdgeInsets.only(left: 0),
                      isScrollable: false,
                      labelPadding: EdgeInsets.symmetric(horizontal:0.0.w),
// 绑定控制器
                      controller: _tabController,
// 定义Tab
                      tabs: [
                        Tab(child:
                        Container(
                          // width: 40.w,
                          height: 20.h,
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text("全部",style: TextStyle(fontSize: 13.sp),),
                              // Badge(label: Text("1"),),
                            ],
                          ),

                        )
                        ),
                        Tab(child:
                        Container(
                          // width: 55.w,
                          height: 20.h,
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text("待签署",style: TextStyle(fontSize: 13.sp),),
                              Badge(backgroundColor: Colors.red,),
                            ],
                          ),

                        )
                        ),

                        Tab(child:
                        Container(
                          // width: 55.w,
                          height: 20.h,
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text("运输中",style: TextStyle(fontSize: 13.sp),),
                              Badge(backgroundColor: Colors.red,),
                            ],
                          ),

                        )
                        ),
                        Tab(child:
                        Container(
                          // width: 55.w,
                          height: 20.h,
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text("运输完成",style: TextStyle(fontSize: 13.sp),),
                              Badge(backgroundColor: Colors.red,),
                            ],
                          ),

                        )
                        ),
                        // Tab(child:
                        // Container(
                        //   width: 55.w,
                        //   height: 20.h,
                        //   child:  Row(
                        //     mainAxisAlignment: MainAxisAlignment.center,
                        //     children: [
                        //       Text("待评价",style: TextStyle(fontSize: 13.sp),),
                        //       Badge(backgroundColor: Colors.red,),
                        //     ],
                        //   ),
                        //
                        // )
                        // ),
                        Tab(child:
                        Container(
                          // width: 55.w,
                          height: 20.h,
                          child:  Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Text("已取消",style: TextStyle(fontSize: 13.sp),),
                              // Badge(label: Text("1"),),
                            ],
                          ),

                        )
                        ),
                      ],
                      labelColor: Color.fromRGBO(231, 112, 27, 0.85),
                      dividerColor: Colors.white,
                      unselectedLabelColor: Colors.black,
                      indicatorColor:Color.fromRGBO(231, 112, 27, 0.85),
                    ),

                    BrnNoticeBar(
                      textColor: Color.fromRGBO(231, 112, 27, 0.85),
                      backgroundColor: Color.fromRGBO(251, 236, 228, 1),
                      content:tipStr,
                      showRightIcon:isShow,

                      // marquee: true,
                      noticeStyle: NoticeStyles.normalNoticeWithArrow,
                      onNoticeTap: () {
                        if(isShow)
                        openAppSettings();
                      },
                      onRightIconTap: () {
                        if(isShow)
                        openAppSettings();
                      },
                    ),
                  ],
                ) ,

              ),

            ),
          ),
        ),


          body:
              TabBarView(
// 绑定控制器
                controller: _tabController,
                children: [
                  AllOrderList(),
                  UnconfirmedList(),
                  RuningOrderList(),
                  EvaluateList(),
                  // EvaluateList(),
                  CancelList(),
                ],

          )




    );

  }



}

class RigthDrawer extends StatefulWidget {
  const RigthDrawer({super.key, required this.type});
  final int type;
  @override
  State<RigthDrawer> createState() => _RigthDrawerState();
}

class _RigthDrawerState extends State<RigthDrawer> {
  List timeList=["1个月内","3个月内","6个月内","今年","2023年","2022年"];
  List orderTypeList=['全部',"确认中",'运输中','待评价','已取消'];
  List desipotList=["全部","可退","不可退","无订金"];
  List isChooseTypeList=["","","","",""];
  bool switchValue = false;
  String startTime="";
  String endTime ="";
  String timeTitle ="请选择时间段";
  String searchStr="";
  Future<DateTime?> _showDatePickerForTheme(BuildContext context) {
    return showDatePicker(
      context: context, // 上下文
      initialDate: DateTime.now(), // 初始化选中日期
      firstDate: DateTime.now(), // 开始日期
      lastDate: DateTime(2100, 1), // 结束日期
      currentDate: DateTime.now(), // 当前日期
      initialEntryMode: DatePickerEntryMode
          .calendarOnly, // 日历弹框样式 calendar: 默认显示日历，可切换成输入模式，input:默认显示输入模式，可切换到日历，calendarOnly:只显示日历，inputOnly:只显示输入模式
      selectableDayPredicate: (dayTime) {
        // 自定义哪些日期可选
        if (dayTime == DateTime(2022, 1, 1) || dayTime == DateTime(2100, 1, 1)) {
          return false;
        }
        return true;
      },
      builder: (context, child) {
        return Theme(
          data: ThemeData(
            primarySwatch: Colors.amber,
          ),
          child: child!,
        );
      },
      helpText: "请选择日期", // 左上角提示文字
      cancelText: "取消", // 取消按钮 文案
      confirmText: "确定", // 确认按钮 文案
      initialDatePickerMode: DatePickerMode.day, // 日期选择模式 默认为天
      useRootNavigator: true, // 是否使用根导航器
      textDirection: TextDirection.ltr, // 水平方向 显示方向 默认 ltr
    );
  }
  double _startX=0;
  @override
  Widget build(BuildContext context) {
    return  GestureDetector(
      onHorizontalDragStart: (details) {
        _startX = details.globalPosition.dx;
      },
      onHorizontalDragUpdate: (details) {
        // Calculate the distance moved
        double deltaX = details.globalPosition.dx - _startX;
        if (deltaX > 50) {
          Navigator.of(context).pop();
        }
      },
      child:
      Drawer(
        elevation: 16.0,
        child: Row(
          children: [
            Container(
              height:   MediaQuery.of(context).size.height,
              width: 30.w,
              child:Column(
                children: [
                  GestureDetector(
                    child:  Container(
                      height:   MediaQuery.of(context).size.height,
                      color:MyColors.backgreyColor,
                    ),
                    onTap: (){
                      Navigator.pop(context);
                    },
                  ),

                ],
              ),
            ),
            Container(
              width: MediaQuery.of(context).size.width- 30.w,
              height:  MediaQuery.of(context).size.height,
              padding: EdgeInsets.only(top: 10.h,bottom: 10.h,left: 10.w,right: 10.w),

              color: Colors.white,
              child: ListView(
                children: [
                  if(widget.type==1)
                    Container(
                      width: MediaQuery.of(context).size.width- 100,
                      height: 30.h,
                      decoration: BoxDecoration(
                          color: MyColors.backgreyColor,
                          borderRadius: BorderRadius.all(Radius.circular(10))),
                      child:  TextField(

                        decoration: InputDecoration(
                          hintText: '搜索我的运单',
                          hintStyle:TextStyle(fontSize: 13.sp,color: MyColors.hintColor),
                          // filled: true,
                          prefixIcon:Icon(Icons.search,size: 20,color: MyColors.authTipColor,),
                          fillColor: MyColors.backgreyColor,
                          border: InputBorder.none,
                          hoverColor:MyColors.themeColor,
                          alignLabelWithHint: true,
                          // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                        ),
                        keyboardType: TextInputType.number,
                        textAlign: TextAlign.left,
                        style: TextStyle(color: Colors.black,fontSize: 13.sp),
                        onChanged: (value) {
                          setState(() {
                            searchStr=value;
                          });
                        },
                      ),
                    ),
                  SizedBox(height: 21.h,),

                  Text("按时间段",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                  SizedBox(height: 8.h,),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Wrap(
                      spacing: 8.w, // 两个Container之间的水平间距
                      runSpacing: 4.h, // 行与行之间的垂直间距
                      children: timeList.map((length) {
                        bool? isSelected = isChooseTypeList.contains(length);
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                isChooseTypeList[0]=[''];
                              } else  {
                                isChooseTypeList[0]=length;

                              }
                            });
                          },
                          child: Container(
                            width: 65.w, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(6.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                  Row(
                    children: [
                      SizedBox(width: 8.w,),
                      GestureDetector(
                        child:  Container(
                          width: 110.w,
                          height: 25.h,
                          decoration: BoxDecoration(
                            color:  MyColors.backgreyColor, // 根据状态决定颜色
                            borderRadius: BorderRadius.circular(6.0), // 设置Container的圆角
                          ),
                          child: Center(
                            child: Text(startTime==""?"起始日期":startTime,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          ),
                        ),
                        onTap: ()async{
                          final result = await showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return dataTimeSheet(
                              );
                            },
                          );

                          if (result != null) {
                            String mounth = "";
                            String day = "";

                            setState(() {
                              if (result[1]
                                  .toString()
                                  .length == 1) {
                                mounth = result[1].toString().padLeft(
                                    2, '0');
                              } else {
                                mounth = result[1].toStringAsFixed(0);
                              }
                              if (result[2]
                                  .toString()
                                  .length == 1) {
                                day = result[2].toString().padLeft(
                                    2, '0');
                              } else {
                                day = result[2].toStringAsFixed(0);
                              }
                              isChooseTypeList[0]="";
                              startTime =
                                  result[0].toString() + "-" + mounth +
                                      "-" + day;

                            });
                          }
                        },
                      ),

                      Text(" - ",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      GestureDetector(
                        child:  Container(
                          width: 110.w,
                          height: 25.h,
                          decoration: BoxDecoration(
                            color:  MyColors.backgreyColor, // 根据状态决定颜色
                            borderRadius: BorderRadius.circular(6.0), // 设置Container的圆角
                          ),
                          child: Center(
                            child: Text(endTime==""?"结束日期":endTime,style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                          ),
                        ),
                        onTap: ()async{
                          final result = await showModalBottomSheet(
                            context: context,
                            builder: (BuildContext context) {
                              return dataTimeSheet(
                              );
                            },
                          );

                          if (result != null) {
                            String mounth = "";
                            String day = "";

                            setState(() {
                              if (result[1]
                                  .toString()
                                  .length == 1) {
                                mounth = result[1].toString().padLeft(
                                    2, '0');
                              } else {
                                mounth = result[1].toStringAsFixed(0);
                              }
                              if (result[2]
                                  .toString()
                                  .length == 1) {
                                day = result[2].toString().padLeft(
                                    2, '0');
                              } else {
                                day = result[2].toStringAsFixed(0);
                              }
                              isChooseTypeList[0]="";
                              endTime =
                                  result[0].toString() + "-" + mounth +
                                      "-" + day;
                              print(endTime);
                            });
                          }
                        },
                      ),

                    ],
                  ),

                  SizedBox(height: 8.h,),
                  Text("运单状态",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                  SizedBox(height: 8.h,),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Wrap(
                      spacing: 8.w, // 两个Container之间的水平间距
                      runSpacing: 4.h, // 行与行之间的垂直间距
                      children: orderTypeList.map((length) {
                        bool? isSelected = isChooseTypeList[1]==length;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                isChooseTypeList[1]=[''];
                              } else  {
                                isChooseTypeList[1]=length;
                              }
                            });
                          },
                          child: Container(
                            width: 65.w, // Container宽度
                            height: 25.h, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(6.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                  SizedBox(height: 8.h,),
                  Text("订金类型",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                  SizedBox(height: 8.h,),
                  Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Wrap(
                      spacing: 8.w, // 两个Container之间的水平间距
                      runSpacing: 4.h, // 行与行之间的垂直间距
                      children: desipotList.map((length) {
                        bool? isSelected = isChooseTypeList[2]==length;
                        return GestureDetector(
                          onTap: () {
                            // 处理点击事件
                            setState(() {
                              if (isSelected) {
                                // 如果已经被选中，则移除
                                isChooseTypeList[2]=[''];
                              } else  {
                                isChooseTypeList[2]=length;
                              }
                            });
                          },
                          child: Container(
                            width: 80.0, // Container宽度
                            height: 30.0, // Container高度，使其成为正方形
                            decoration: BoxDecoration(
                              color: isSelected ? Color.fromRGBO(251, 236, 228, 1) : MyColors.backgreyColor, // 根据状态决定颜色
                              borderRadius: BorderRadius.circular(6.0), // 设置Container的圆角
                            ),
                            child: Center(
                              child: Text(
                                length,
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: isSelected ?MyColors.themeColor:Colors.black, // 文字颜色为白色
                                ),
                              ),
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                  ),
                  SizedBox(height: 8.h,),

                  SizedBox(height:50.h ,),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [

                      BrnSmallOutlineButton(
                        textColor: MyColors.themeColor,
                        lineColor: MyColors.themeColor,
                        radius: 30,
                        width: 120.w,
                        fontSize: 14.sp,
                        title: '重置',
                        onTap: () {
                          isChooseTypeList=["","","",""];
                        },
                      ),
                      SizedBox(width: 20.w,),
                      BrnSmallMainButton(
                        bgColor: MyColors.themeColor,
                        textColor: Colors.white,
                        radius: 30,
                        width: 120.w,
                        fontSize: 14.sp,
                        title: '确定',
                        onTap: () {
                          isChooseTypeList[4]=searchStr;
                          if(isChooseTypeList[0]!=""){
                            if(startTime!=""){
                              startTime=startTime.substring(0,10);
                              endTime=endTime.substring(0,10);
                            }
                            if(isChooseTypeList[0]=="今年"){
                              startTime="2024-01-01";
                              endTime="2024-12-31";
                            }else  if(isChooseTypeList[0]=="2023年"){
                              startTime="2023-01-01";
                              endTime="2023-12-31";
                            }else  if(isChooseTypeList[0]=="2022年"){
                              startTime="2022-01-01";
                              endTime="2022-12-31";
                            }

                          }
                          Map dataMap={
                            "category":isChooseTypeList[1]=="确认中"?1:isChooseTypeList[1]=="运输中"?
                            2:isChooseTypeList[1]=="待评价"? 3:isChooseTypeList[1]=="已取消"?4:0,
                            "searchKey":searchStr,
                            "periodMonth":isChooseTypeList[0]=="1个月内"?1:isChooseTypeList[0]=="3个月内"?3:isChooseTypeList[0]=="6个月内"?3:0,
                            "periodFrom":startTime,
                            "periodTo":endTime,
                            "depositType":isChooseTypeList[2]=="退还"?0:isChooseTypeList[2]=="不退还"?1:isChooseTypeList[2]=="无订金"?-1:null,
                          };
                          print(dataMap);
                          print(isChooseTypeList);
                          Navigator.pop(context);
                          Navigator.push( context, FadeRoute(page:FilterResultsVIew(dataMap: dataMap,
                          )));


                        },
                      )
                    ],
                  )
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}